package com.yang.demo.util;

import android.util.Log;

import com.google.gson.Gson;
import com.yang.demo.Model;
import com.yang.demo.ProjectApplication;
import com.yang.demo.greendao.DaoManager;

import org.json.JSONArray;
import org.json.JSONObject;

import java.io.InputStream;

import jxl.Cell;
import jxl.Sheet;
import jxl.Workbook;

/**
 * Created by mc on 2018/3/19.
 */
public class XlsToJson {

    private static InputStream is;
    private static Gson gson;

    public XlsToJson() {
    }

    public static void start() {
        gson = new Gson();
        Sheet sheet;
        Workbook book;
        Cell cell1, cell2, cell3, cell4, cell5, cell6, cell7, cell8, cell9, cell10;
        JSONArray array = new JSONArray();
        DaoManager daoManager = DaoManager.getInstance();
        try {
            is = ProjectApplication.getApplication().getAssets().open("movie.xls");
            //为要读取的excel文件名
            book = Workbook.getWorkbook(is);

            //获得第一个工作表对象(ecxel中sheet的编号从0开始,0,1,2,3,....)
            sheet = book.getSheet(0);

            for (int i = 1; i < sheet.getRows(); i++) {
                //获取每一行的单元格
                cell1 = sheet.getCell(0, i);//（列，行）
                cell2 = sheet.getCell(1, i);
                cell3 = sheet.getCell(2, i);
                cell4 = sheet.getCell(3, i);
                cell5 = sheet.getCell(4, i);
                cell6 = sheet.getCell(6, i);
                cell7 = sheet.getCell(7, i);
                cell8 = sheet.getCell(8, i);
                cell9 = sheet.getCell(9, i);
                cell10 = sheet.getCell(10, i);
                if ("".equals(cell1.getContents())) {//如果读取的数据为空
                    break;
                }
                JSONObject object = new JSONObject();
                object.put("id", cell1.getContents());
                object.put("name", cell2.getContents());
                object.put("year", cell3.getContents());
                object.put("area", cell4.getContents());
                object.put("score", cell5.getContents());
                object.put("content", cell6.getContents());
                object.put("img", cell7.getContents());
                object.put("director", cell8.getContents());
                object.put("keyword", cell9.getContents());
                object.put("type", cell10.getContents());
                array.put(object);
                Log.e("test", object.toString());
                daoManager.insertData(gson.fromJson(object.toString(), Model.class));
            }
            book.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}